import React, {Component, Fragment} from 'react'
import {render} from "react-dom"
import axios from 'axios'

export default class Signup extends Component {
  constructor(props) {
    super(props)
    this.state = {
      'username': '',
      'password': '',
      error: ''
    }
  }

  onChangeUsername = (e) => {
    this.setState({username: e.target.value})
  }

  onChangePassword = (e) => {
    this.setState({password: e.target.value})
  }

  onSubmit = (e) => {
    e.preventDefault();
    axios.post('http://127.0.0.1:8000/auth/users/', this.state).then(res => {
      console.log(res.data)
      this.props.history.push('/signin')
    }).catch((err) => { // if (err.response) {
      console.log('err.response.data.detail', err.response.data);
      if (err.response.data.password) {
        this.setState({error: err.response.data.password.join(',')})

      } else if (err.response.data.username) {
        this.setState({error: err.response.data.username.join(',')})
      }
      // }
    });
  }

  render() {
    return (
      <form onSubmit={
        this.onSubmit
      }>
        <div class="form-group">
          <label for="exampleInputEmail1">姓名</label>
          <input type="text"
            value={
              this.state.username
            }
            onChange={
              this.onChangeUsername
            }
            name="username"
            class="form-control"
            id="exampleInputEmail1"
            aria-describedby="emailHelp"
            placeholder="请输入你的姓名"/>
        </div>
        <div class="form-group">
          <label for="exampleInputPassword1">密码</label>
          <input type="password"
            value={
              this.state.password
            }
            onChange={
              this.onChangePassword
            }
            name="password"
            class="form-control"
            id="exampleInputPassword1"
            placeholder="请输入你的密码"/></div>

        {/* <div class="form-check">
          <input type="checkbox" class="form-check-input" id="exampleCheck1"/>
          <label class="form-check-label" for="exampleCheck1">Check me out</label>
        </div> */}
        <button type="submit" class="btn btn-primary">注册</button>
        <br/>
        <br/>
        <Fragment>{
          this.state.error ? <span className="alert alert-danger">
            {
            this.state.error
          }</span> : null
        }</Fragment>
      </form>
    )
  }

}
